<template>
  <div class="statistics-container">
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="filterForm.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="filterForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="院区">
          <el-select v-model="filterForm.campusId" placeholder="选择院区" clearable>
            <el-option label="全部院区" :value="0" />
            <el-option
              v-for="campus in campuses"
              :key="campus.id"
              :label="campus.name"
              :value="campus.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchStatistics">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button @click="exportReport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计摘要 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="summary-title">总核验数</div>
            <div class="summary-value">{{ statistics.summary.total_verifications }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="summary-title">通过数</div>
            <div class="summary-value success">{{ statistics.summary.pass_count }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="summary-title">拒绝数</div>
            <div class="summary-value danger">{{ statistics.summary.reject_count }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="summary-card">
          <div class="summary-item">
            <div class="summary-title">特殊访客</div>
            <div class="summary-value warning">{{ statistics.summary.special_visitor_count }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>每日趋势</span>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>院区统计</span>
            </div>
          </template>
          <div ref="campusChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 特殊访客统计 -->
    <el-row :gutter="20" class="special-stats-row">
      <el-col :span="24">
        <el-card class="special-stats-card">
          <template #header>
            <div class="card-header">
              <span>特殊访客统计</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="special-stat-item">
                <div class="special-stat-title">VIP访客</div>
                <div class="special-stat-value">{{ statistics.special_visitor_stats.vip }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="special-stat-item">
                <div class="special-stat-title">纠纷访客</div>
                <div class="special-stat-value">{{ statistics.special_visitor_stats.dispute }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="special-stat-item">
                <div class="special-stat-title">其他访客</div>
                <div class="special-stat-value">{{ statistics.special_visitor_stats.other }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import type { Campus } from '@/types/superadmin'
import { superAdminApi } from '@/api/superadmin'
import { showError, showSuccess, showWarning } from '@/utils/message'
import type { StatisticsData } from '@/api/superadmin'

// 初始化筛选表单
const filterForm = reactive({
  startDate: '',
  endDate: '',
  campusId: undefined as number | undefined
})

// 院区列表
const campuses = ref<Campus[]>([])

// 初始化统计数据
const statistics = ref<StatisticsData>({
  summary: {
    total_verifications: 0,
    pass_count: 0,
    reject_count: 0,
    special_visitor_count: 0,
    pass_rate: 0
  },
  daily_trend: [],
  campus_stats: [],
  special_visitor_stats: {
    vip: 0,
    dispute: 0,
    other: 0
  }
})

// 图表引用
const trendChartRef = ref<HTMLDivElement | null>(null)
const campusChartRef = ref<HTMLDivElement | null>(null)
let trendChart: echarts.ECharts | null = null
let campusChart: echarts.ECharts | null = null

// 获取院区列表
const fetchCampuses = async () => {
  try {
    const response = await superAdminApi.getCampuses({ page: 1, size: 100 })
    // 由于响应拦截器已经处理了响应格式，这里直接获取数据
    campuses.value = response.items || []
  } catch (error) {
    console.error('获取院区列表失败:', error)
    showError('获取院区列表失败')
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 验证必填字段
    if (!filterForm.startDate || !filterForm.endDate) {
      showWarning('请选择开始日期和结束日期')
      return
    }

    // 构造请求参数
    const params: any = {
      start_date: filterForm.startDate,
      end_date: filterForm.endDate
    }

    if (filterForm.campusId && filterForm.campusId !== 0) {
      params.campus_id = filterForm.campusId
    }

    // 调用后端API获取统计数据
    const response = await superAdminApi.getStatistics(params)
    if (response.code === 200 && response.data) {
      statistics.value = response.data
    }
    
    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取统计数据失败:', error)
    showError('获取统计数据失败')
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.startDate = ''
  filterForm.endDate = ''
  filterForm.campusId = undefined
}

// 导出报表
const exportReport = async () => {
  try {
    showWarning('导出报表功能待实现')
  } catch (error) {
    console.error('导出报表失败:', error)
    showError('导出报表失败')
  }
}

// 更新趋势图表
const updateTrendChart = () => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dates = statistics.value.daily_trend.map(item => item.date)
  const totals = statistics.value.daily_trend.map(item => item.total)
  const pass = statistics.value.daily_trend.map(item => item.pass)
  const reject = statistics.value.daily_trend.map(item => item.reject)

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总核验数', '通过数', '拒绝数']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总核验数',
        type: 'line',
        data: totals,
        smooth: true
      },
      {
        name: '通过数',
        type: 'line',
        data: pass,
        smooth: true
      },
      {
        name: '拒绝数',
        type: 'line',
        data: reject,
        smooth: true
      }
    ]
  }

  trendChart.setOption(option)
}

// 更新院区统计图表
const updateCampusChart = () => {
  if (!campusChartRef.value) return

  if (!campusChart) {
    campusChart = echarts.init(campusChartRef.value)
  }

  const campusNames = statistics.value.campus_stats.map(item => item.campus_name)
  const totals = statistics.value.campus_stats.map(item => item.total)
  const pass = statistics.value.campus_stats.map(item => item.pass)
  const reject = statistics.value.campus_stats.map(item => item.reject)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总核验数', '通过数', '拒绝数']
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: campusNames
    },
    series: [
      {
        name: '总核验数',
        type: 'bar',
        stack: '总量',
        data: totals
      },
      {
        name: '通过数',
        type: 'bar',
        stack: '总量',
        data: pass
      },
      {
        name: '拒绝数',
        type: 'bar',
        stack: '总量',
        data: reject
      }
    ]
  }

  campusChart.setOption(option)
}

// 更新所有图表
const updateCharts = () => {
  updateTrendChart()
  updateCampusChart()
}

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (trendChart) {
    trendChart.resize()
  }
  if (campusChart) {
    campusChart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 设置默认日期范围为最近7天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 7)
  
  filterForm.startDate = startDate.toISOString().split('T')[0] || ''
  filterForm.endDate = endDate.toISOString().split('T')[0] || ''
  
  // 获取院区列表
  fetchCampuses()
  
  // 获取初始统计数据
  fetchStatistics()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
// onUnmounted(() => {
//   window.removeEventListener('resize', handleResize)
//   if (trendChart) {
//     trendChart.dispose()
//   }
//   if (campusChart) {
//     campusChart.dispose()
//   }
// })

// 监听统计数据变化，更新图表
watch(() => statistics.value, () => {
  updateCharts()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.summary-row {
  margin-bottom: 20px;
}

.summary-card {
  height: 120px;
}

.summary-item {
  text-align: center;
  padding: 20px 0;
}

.summary-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
}

.summary-value.success {
  color: #67c23a;
}

.summary-value.danger {
  color: #f56c6c;
}

.summary-value.warning {
  color: #e6a23c;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  font-weight: bold;
}

.chart-container {
  width: 100%;
  height: 320px;
}

.special-stats-card {
  height: 150px;
}

.special-stat-item {
  text-align: center;
  padding: 20px 0;
}

.special-stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.special-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}
</style>